﻿
namespace PokerSimulator
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;

	using PugLib.Extensions.Collections;

	public class Deck
	{
		private readonly List<Card> _cards;
		private readonly Stack<Card> _deck;

		public Deck()
		{
			_cards = GetUnshuffledDeck();
			_deck = new Stack<Card>(52);
			ShuffleCards();
		}

		private void ShuffleCards()
		{
			_deck.Clear();
			// the order by Guid offers 99.9% uniqueness over 1 million decks!
			IOrderedEnumerable<Card> randomCards = _cards.OrderBy(a => Guid.NewGuid());
			randomCards.ForEach(c => _deck.Push(c));
		}

		private static List<Card> GetUnshuffledDeck()
		{
			List<Card> cards = new List<Card>();
			for (int i = Card.SmallestCardValue; i <= Card.LargestCardValue; i++)
			{
				char[] suits = Statics.Suits;
				foreach (char suit in suits)
				{
					cards.Add(new Card(i, suit));
				}
			}
			return cards;
		}

		public Card DealCard()
		{
			return _deck.Pop();
		}

		public void Shuffle()
		{
			ShuffleCards();
		}

		public override string ToString()
		{
			StringBuilder sb = new StringBuilder();
			Card[] deck = _deck.ToArray();
			foreach (Card c in deck)
			{
				sb.Append(c);
			}
			return sb.ToString();
		}
	}
}